﻿using Canteen.Core.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Security.Authentication;

namespace Canteen.Core.Common
{
    public class GlobalExceptionHandlerFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            //异常是否处理
            if (context.ExceptionHandled) return;

            //客服端请求参数有误 Status 400  
            if (context.Exception is ArgumentException ||           //传给函数的参数异常。
                context.Exception is FormatException ||             //格式转换异常
                context.Exception is JsonSerializationException)    //json序列化失败
            {
                context.Result = new ObjectResult(HttpResult<string>.Fail(400,context.Exception.Message))
                {
                    StatusCode = StatusCodes.Status200OK
                };
            }
            else if (context.Exception is CustomLockedException)//自定义资源被锁定异常
            {
                context.Result = new ObjectResult(HttpResult<string>.Fail(423, context.Exception.Message))
                {
                    StatusCode = StatusCodes.Status200OK//.Status423Locked
                };
            }
            else if (context.Exception is AuthenticationException)
            {
                context.Result = new ObjectResult(HttpResult<string>.Fail(401, context.Exception.Message))
                {
                    StatusCode = StatusCodes.Status200OK//.Status401Unauthorized
                };
            }
            else
            {
                context.Result = new ObjectResult(HttpResult<string>.Fail(context.Exception.Message))
                {
                    StatusCode = StatusCodes.Status200OK//.Status422UnprocessableEntity
                };
                //context.Result = new objectre(context.Exception.Message);
            }

            //下面进行异常处理的逻辑，可以记录日志、返回前端友好提示等
            //...
            //StringBuilder sb = new StringBuilder();
            //sb.AppendLine($"服务发生异常: {context.Exception.Message}");
            //sb.AppendLine(context.Exception.ToString());
            //Logger.LogCritical(sb.ToString());
            //throw new NotImplementedException();

            //设置异常已经处理,否则会被其他异常过滤器覆盖
            context.ExceptionHandled = true;
        }
    }
}